<template>
  <div
    v-loading="loading"
    element-loading-text="处理中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    style="padding:0;height:100%;display:flex;flex-direction:column"
  >
    <el-row style="margin-bottom:10px;">
      <el-col :span="5">
        初始化将按照sqlId升序排序！！！
      </el-col>
    </el-row>
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-button type="primary" @click="handleAdd" :disabled="disabled" style="width:75px;">添加项</el-button>
        <el-button type="success" @click="handleSave" :disabled="disabled" style="width:75px;">保存</el-button>
        <el-button type="danger" @click="handleExecute" style="width:75px;">执行</el-button>
      </el-col>
      <el-col :span="24">
        <svn-box
          ref="svn"
          propSourceType="init-data"
          :propShowAdd="false"
          :propShowDelete="false"
          @set-loading="handleSvnSetLoading"
          @lock-status-change="handleLockStatusChange"
        />
      </el-col>
    </el-row>
    <div style="height:calc(100vh - 230px);overflow:auto">
      <div style="display:flex;align-items:center;">
        <el-input v-model="filter" style="width:400px;margin-bottom:10px;" placeholder="表名/sql/描述的过滤条件"></el-input>
        <div style="margin-left:30px;">count: <label>{{sqlStore.count}}</label></div>
        <div style="margin-left:30px;">lastId: <label>{{sqlStore.lastId}}</label></div>
      </div>

      <el-tabs v-model="selectedTab" type="border-card">
        <el-tab-pane
          :key="item.id"
          v-for="(item,index) in cpItems"
          :label="item.tables+''+item.description"
          :name="item.id + ''"
        >
          <div style="display:flex;align-items:center;width:100%">
            <el-button
              type="text"
              :disabled="disabled"
              @click="handleRemove(item, index)"
              style="margin:10px;"
            >删除</el-button>
            <el-form
              :disabled="disabled"
              :model="item"
              :ref="getFormName(item.id)"
              :rules="rules"
              label-position="right"
              label-width="120px"
              style="width:95%"
            >
              <el-row :gutter="10">
                <el-col :span="3">
                  <el-form-item label="id"><el-input disabled :value="item.id"></el-input></el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="作者" prop="author"><el-input v-model="item.author"></el-input></el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label="时间"><el-input disabled :value="item.time"></el-input></el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="表(s)" prop="tables"><el-input v-model="item.tables"></el-input></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="说明"><el-input v-model="item.description"></el-input></el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item label="" prop="sql">
                    <el-input type="textarea"  v-model="item.sql" :autosize="{minRows: 27, maxRows: 27}" placeholder="sql"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!--<el-card v-for="(item,index) in cpItems" :key="item.id" style="margin-bottom:10px">
        <div style="display:flex;align-items:center;width:100%">
          <el-button
            type="text"
            :disabled="disabled"
            @click="handleRemove(item, index)"
            style="margin:10px;"
          >删除</el-button>
          <el-form
            :disabled="disabled"
            :model="item"
            :ref="getFormName(item.id)"
            :rules="rules"
            label-position="right"
            label-width="60px"
            style="width:95%"
          >
            <el-row :gutter="10">
              <el-col :span="3">
                <el-form-item label="id"><el-input disabled :value="item.id"></el-input></el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="作者" prop="author"><el-input v-model="item.author"></el-input></el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="时间"><el-input disabled :value="item.time"></el-input></el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="表(s)" prop="tables"><el-input v-model="item.tables"></el-input></el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="说明"><el-input v-model="item.description"></el-input></el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="" prop="sql">
                  <el-input type="textarea" :rows="3" v-model="item.sql" placeholder="sql"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>-->
    </div>
  </div>
</template>

<script>
import SvnBox from '@/components/SvnBox.vue'

export default {
  name: 'frameInitData',
  data() {
    return {
      selectedTab: null,
      sqlStore: {},
      filter: '',
      svnUserName: '',
      loading: false,
      disabled: true,
      rules: {
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        tables: [
          { required: true, message: '请描述要操作的表', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        sql: [
          { required: true, message: '请输入处理的SQL', trigger: 'blur' },
          { min: 10, max: 50000, message: '长度在 10 到 50000 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    SvnBox
  },
  mounted() {
    this.$refs.svn.ocSetFileName()
    this.handleRefresh()
  },
  computed: {
    cpItems() {
      if (this.filter == '') {
        return this.sqlStore.items
      } else {
        return this.sqlStore.items.filter(item => {
          return item.tables.indexOf(this.filter) > -1
              || item.sql.indexOf(this.filter) > -1
              || item.description.indexOf(this.filter) > -1
        })
      }
    }
  },
  methods: {
    handleNodeClick(node, data) {
      this.selectedMenu = data
    },
    getFormName(id) {
      return 'form_' + id
    },
    getMaxId() {
      return this.sqlStore.lastId ? this.sqlStore.lastId : 0
    },
    handleRemove(item, index) {
      this.sqlStore.items.splice(index, 1)
      this.sqlStore.count = this.sqlStore.items.length
    },
    handleAdd() {
      const newChild = {
        id: this.getMaxId() + 1,
        author: this.svnUserName,
        time: global.utils.now(),
        tables: '',
        description: '',
        sql: ''
      }
      this.sqlStore.items.unshift(newChild)
      this.sqlStore.count = this.sqlStore.items.length
      this.sqlStore.lastId = newChild.id
    },
    // == SVN START===
    handleSvnSetLoading(loading) {
      this.loading = loading
    },
    handleLockStatusChange(status) {
      this.disabled = !['LOCK_BY_SELF', 'DRAFT', 'ADDED'].includes(status.lockStatus)
      this.svnUserName = status.userName
      // 锁定时要先获取最新版本，所以要重新获取记录
      if (status.lockStatus == 'LOCK_BY_SELF') {
        this.handleRefresh()
      }
    },
    // == SVN END==
    handleRefresh() {
      this.loading = true
      this.$ajax.get('/program/initData/getList').then(res => {
        this.sqlStore = JSON.parse(res.data)
        this.selectedTab = this.cpItems[0] ? this.cpItems[0].tables : ''
      }).finally(() => {
        this.loading = false
      })
    },
    handleExecute() {
      this.loading = true
      this.$ajax.post('/program/initData/execute').then(res => {
        this.utilMessage.success(res.msg)
      }).finally(() => {
        this.loading = false
      })
    },
    asyncValidate(form) {
      return new Promise((resolve, reject) => {
        form.validate((state) => {
          resolve(state)
        })
      })
    },
    async handleSave() {
      // for (let index = 0; index < this.sqlStore.items.length; index += 1) {
      //   const formName = this.getFormName(this.sqlStore.items[index].id)
      //   const form = this.$refs[formName][0] || this.$refs[formName]
      //   const state = await this.asyncValidate(form)
      //   if (!state) return
      // }
      this.loading = true
      this.sqlStore.count = this.sqlStore.items.length
      this.$ajax.post('/program/initData/save', { contents: JSON.stringify(this.sqlStore) }).then(res => {
        if (res.code == 0) {
          this.utilMessage.success('数据保存成功！')
        } else {
          this.utilMessage.error(`初始化数据保存返回错误信息${res.msg}`)
        }
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .custom-tree-node {
    flex: 1;
    margin:10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 8px;
  }
  .custom-tree-title {
    font-size:14px;
  }
  .svn-status-container {
     padding:5px;
     font-size:18px;
  }
  .svn-status-icon {
     margin-right:5px;
     font-weight: bold;
     font-size:20px;
  }
  .green {
    color:darkgreen;
  }
  .grey {
    color:grey;
  }
  .red {
    color:red;
  }
</style>
